############################
##Conjoint analysis 2017
############################

#This script was run on the following R version, platform and OS:
#R version 3.6.3 (2020-02-29)
#Platform: x86_64-apple-darwin15.6.0 (64-bit)
#Running under: macOS Sierra 10.12.6

rm(list = ls())  # clear

#Load packages - please install if missing (package version used is indicated)
require(readstata13) #0.9.2
require(ggplot2) #3.3.0
require(GPArotation) #2014.11-1
require(cregg) #0.3.0
require(dplyr) #0.8.5
require(dotwhisker) #0.5.0
require(stringr) #1.4.0
require(xtable) #1.8-4
require(psych) #1.9.12.31
require(random.polychor.pa) #1.1.4-3

#Create directories
dir.create("Graphs") 
dir.create("Tables") 

#Load data from 2017
conjoint_data <- read.dta13("data_conjoint_2017_R.dta", nonint.factors = TRUE)


################################################
#Transform German to English data & Stata to R
################################################

#Translation of attributes
conjoint_data$fluechtlinge <- factor(conjoint_data$fluechtlinge, levels = c(1, 2, 3, 4), labels = c("Is for the deportation of some refugees", "Is for the deportation of a great many refugees", "Is for the admission of some new refugees", "Is for the admission of a great many new refugees"))
conjoint_data$steuern <- factor(conjoint_data$steuern, levels = c("Ist für etwas höhere Steuern für Reiche", "Ist für etwas niedrigere Steuern für Reiche", "Ist für sehr viel höhere Steuern für Reiche", "Ist für sehr viel niedrigere Steuern für Reiche"), labels = c("Is for somewhat higher taxes on the rich", "Is for somewhat lower taxes on the rich", "Is for much higher taxes on the rich","Is for much lower taxes on the rich"))
conjoint_data$EU <- factor(conjoint_data$EU, levels = c("Ist für den Ausbau der Europäischen Union zu einem gemeinsamen Staat", "Ist für den Austritt Deutschlands aus der Europäischen Union", "Ist für eine schwächere Zusammenarbeit in der Europäischen Union", "Ist für eine stärkere Zusammenarbeit in der Europäischen Union"), labels = c("Is for the development of the EU into a common state", "Is for Germany's withdrawal from the EU", "Is for weaker cooperation within the EU", "Is for stronger cooperation within the EU"))
conjoint_data$freihandel <- factor(conjoint_data$freihandel, levels = c("Ist für etwas mehr Freihandel und Globalisierung", "Ist für etwas weniger Freihandel und Globalisierung", "Ist für viel mehr Freihandel und Globalisierung", "Ist für viel weniger Freihandel und Globalisierung"), labels = c("Is for somewhat more free trade and globalization", "Is for somewhat less free trade and globalization", "Is for much more free trade and globalization", "Is for much less free trade and globalization"))
conjoint_data$schwerpunkt1 <- factor(conjoint_data$schwerpunkt1, levels = c("Bürgerrechte und Freiheitsrechte stärken", "Deutschland aus der Krise führen", "Die politische Elite entmachten", "Direkte Demokratie stärken (z.B. Volksentscheide)", "Ein soziales Europa schaffen", "Globalisierung gerechter gestalten", "Interessen der Bürger verteidigen", "Islamisierung stoppen", "Korruption in der Politik bekämpfen", "Kriminalität bekämpfen", "Soziale Gerechtigkeit stärken", "Umweltschutz verbessern", "Wirtschaftswachstum fördern"), labels = c("Strengthen civil rights and civil liberties", "Lead Germany out of the crisis", "Overthrow the political elite", "Strengthen direct democracy (e.g., through referendums)", "Create a social Europe", "Make globalization fairer", "Defend citizens' interests", "Stop Islamization", "Fight political corruption", "Fight crime", "Strengthen social justice", "Improve environmental protection", "Promote economic growth"))
conjoint_data$schwerpunkt2 <- factor(conjoint_data$schwerpunkt2, levels = c("Bürgerrechte und Freiheitsrechte stärken", "Deutschland aus der Krise führen", "Die politische Elite entmachten", "Direkte Demokratie stärken (z.B. Volksentscheide)", "Ein soziales Europa schaffen", "Globalisierung gerechter gestalten", "Interessen der Bürger verteidigen", "Islamisierung stoppen", "Korruption in der Politik bekämpfen", "Kriminalität bekämpfen", "Soziale Gerechtigkeit stärken", "Umweltschutz verbessern", "Wirtschaftswachstum fördern"), labels = c("Strengthen civil rights and civil liberties", "Lead Germany out of the crisis", "Overthrow the political elite", "Strengthen direct democracy (e.g., through referendums)", "Create a social Europe", "Make globalization fairer", "Defend citizens' interests", "Stop Islamization", "Fight political corruption", "Fight crime", "Strengthen social justice", "Improve environmental protection", "Promote economic growth"))

#Change names of attributes
conjoint_data$A1_refugees <- conjoint_data$fluechtlinge
conjoint_data$A2_EU <- conjoint_data$EU
conjoint_data$A3_tax <- conjoint_data$steuern
conjoint_data$A4_trade <- conjoint_data$freihandel
conjoint_data$A5_priority1 <- conjoint_data$schwerpunkt1
conjoint_data$A6_priority2 <- conjoint_data$schwerpunkt2

#Reorder levels of factor variables
conjoint_data$A1_refugees <- factor(conjoint_data$A1_refugees, levels = c("Is for the admission of a great many new refugees", "Is for the admission of some new refugees", "Is for the deportation of some refugees", "Is for the deportation of a great many refugees"))
conjoint_data$A3_tax <- factor(conjoint_data$A3_tax, levels = c("Is for much higher taxes on the rich", "Is for somewhat higher taxes on the rich", "Is for somewhat lower taxes on the rich", "Is for much lower taxes on the rich"))
conjoint_data$A2_EU<- factor(conjoint_data$A2_EU, levels = c("Is for the development of the EU into a common state", "Is for stronger cooperation within the EU", "Is for weaker cooperation within the EU", "Is for Germany's withdrawal from the EU"))
conjoint_data$A4_trade <- factor(conjoint_data$A4_trade, levels = c("Is for much more free trade and globalization", "Is for somewhat more free trade and globalization", "Is for somewhat less free trade and globalization", "Is for much less free trade and globalization"))
conjoint_data$A5_priority1 <- factor(conjoint_data$A5_priority1, levels = c("Fight political corruption", "Overthrow the political elite", "Strengthen direct democracy (e.g., through referendums)", "Defend citizens' interests", "Lead Germany out of the crisis", "Improve environmental protection", "Promote economic growth", "Strengthen social justice", "Stop Islamization", "Fight crime", "Strengthen civil rights and civil liberties", "Make globalization fairer", "Create a social Europe"))    
conjoint_data$A6_priority2 <- factor(conjoint_data$A6_priority2, levels = c("Fight political corruption", "Overthrow the political elite", "Strengthen direct democracy (e.g., through referendums)", "Defend citizens' interests", "Lead Germany out of the crisis", "Improve environmental protection", "Promote economic growth", "Strengthen social justice", "Stop Islamization", "Fight crime", "Strengthen civil rights and civil liberties", "Make globalization fairer", "Create a social Europe"))    

#Create binary priorities
conjoint_data$B1_corruption <- "No priority1"
conjoint_data$B1_corruption[conjoint_data$A5_priority1 == "Fight political corruption"] <- "Priority1"
conjoint_data$B1_corruption[conjoint_data$A6_priority2 == "Fight political corruption"] <- "Priority1"
conjoint_data$B1_corruption <- factor(conjoint_data$B1_corruption, levels = c("No priority1", "Priority1"))

conjoint_data$B2_elite <- "No priority2"
conjoint_data$B2_elite[conjoint_data$A5_priority1 == "Overthrow the political elite"] <- "Priority2"
conjoint_data$B2_elite[conjoint_data$A6_priority2 == "Overthrow the political elite"] <- "Priority2"
conjoint_data$B2_elite <- factor(conjoint_data$B2_elite, levels = c("No priority2", "Priority2"))

conjoint_data$B3_democracy <- "No priority3"
conjoint_data$B3_democracy[conjoint_data$A5_priority1 == "Strengthen direct democracy (e.g., through referendums)"] <- "Priority3"
conjoint_data$B3_democracy[conjoint_data$A6_priority2 == "Strengthen direct democracy (e.g., through referendums)"] <- "Priority3"
conjoint_data$B3_democracy <- factor(conjoint_data$B3_democracy, levels = c("No priority3", "Priority3"))

conjoint_data$B4_citizens <- "No priority4"
conjoint_data$B4_citizens[conjoint_data$A5_priority1 == "Defend citizens' interests"] <- "Priority4"
conjoint_data$B4_citizens[conjoint_data$A6_priority2 == "Defend citizens' interests"] <- "Priority4"
conjoint_data$B4_citizens <- factor(conjoint_data$B4_citizens, levels = c("No priority4", "Priority4"))

conjoint_data$B5_crisis <- "No priority5"
conjoint_data$B5_crisis[conjoint_data$A5_priority1 == "Lead Germany out of the crisis"] <- "Priority5"
conjoint_data$B5_crisis[conjoint_data$A6_priority2 == "Lead Germany out of the crisis"] <- "Priority5"
conjoint_data$B5_crisis <- factor(conjoint_data$B5_crisis, levels = c("No priority5", "Priority5"))

conjoint_data$B6_environment <- "No priority6"
conjoint_data$B6_environment[conjoint_data$A5_priority1 == "Improve environmental protection"] <- "Priority6"
conjoint_data$B6_environment[conjoint_data$A6_priority2 == "Improve environmental protection"] <- "Priority6"
conjoint_data$B6_environment <- factor(conjoint_data$B6_environment, levels = c("No priority6", "Priority6"))

conjoint_data$B7_growth <- "No priority7"
conjoint_data$B7_growth[conjoint_data$A5_priority1 == "Promote economic growth"] <- "Priority7"
conjoint_data$B7_growth[conjoint_data$A6_priority2 == "Promote economic growth"] <- "Priority7"
conjoint_data$B7_growth <- factor(conjoint_data$B7_growth, levels = c("No priority7", "Priority7"))

conjoint_data$B8_justice <- "No priority8"
conjoint_data$B8_justice[conjoint_data$A5_priority1 == "Strengthen social justice"] <- "Priority8"
conjoint_data$B8_justice[conjoint_data$A6_priority2 == "Strengthen social justice"] <- "Priority8"
conjoint_data$B8_justice <- factor(conjoint_data$B8_justice, levels = c("No priority8", "Priority8"))

conjoint_data$B9_islamization <- "No priority9"
conjoint_data$B9_islamization[conjoint_data$A5_priority1 == "Stop Islamization"] <- "Priority9"
conjoint_data$B9_islamization[conjoint_data$A6_priority2 == "Stop Islamization"] <- "Priority9"
conjoint_data$B9_islamization <- factor(conjoint_data$B9_islamization, levels = c("No priority9", "Priority9"))

conjoint_data$C1_crime <- "No priority10"
conjoint_data$C1_crime[conjoint_data$A5_priority1 == "Fight crime"] <- "Priority10"
conjoint_data$C1_crime[conjoint_data$A6_priority2 == "Fight crime"] <- "Priority10"
conjoint_data$C1_crime <- factor(conjoint_data$C1_crime, levels = c("No priority10", "Priority10"))

conjoint_data$C2_liberties <- "No priority11"
conjoint_data$C2_liberties[conjoint_data$A5_priority1 == "Strengthen civil rights and civil liberties"] <- "Priority11"
conjoint_data$C2_liberties[conjoint_data$A6_priority2 == "Strengthen civil rights and civil liberties"] <- "Priority11"
conjoint_data$C2_liberties <- factor(conjoint_data$C2_liberties, levels = c("No priority11", "Priority11"))

conjoint_data$C3_globalization <- "No priority12"
conjoint_data$C3_globalization[conjoint_data$A5_priority1 == "Make globalization fairer"] <- "Priority12"
conjoint_data$C3_globalization[conjoint_data$A6_priority2 == "Make globalization fairer"] <- "Priority12"
conjoint_data$C3_globalization <- factor(conjoint_data$C3_globalization, levels = c("No priority12", "Priority12"))

conjoint_data$C4_europe <- "No priority13"
conjoint_data$C4_europe[conjoint_data$A5_priority1 == "Create a social Europe"] <- "Priority13"
conjoint_data$C4_europe[conjoint_data$A6_priority2 == "Create a social Europe"] <- "Priority13"
conjoint_data$C4_europe <- factor(conjoint_data$C4_europe, levels = c("No priority13", "Priority13"))

#Rename main dataset
conjoint_2017 <- conjoint_data
conjoint_2017$lfdn <- conjoint_2017$lfdn_W3


##############################
#Run main conjoint analyses
##############################

#Full results for all respondents
results_main <- cj(praeferenz ~ 
                     A1_refugees + 
                     A2_EU +
                     A3_tax + 
                     A4_trade +
                     B1_corruption + B2_elite + B3_democracy + B4_citizens + B5_crisis + B6_environment + B7_growth + B8_justice + B9_islamization + C1_crime + C2_liberties + C3_globalization + C4_europe, 
                   data = conjoint_2017, id = ~lfdn, weights = ~weight_wave3, estimate = "mm")

names(results_main)[4]="term"
results_main <- results_main[!is.na(results_main$estimate) & str_sub(levels(results_main$term), 1, 2) != "No",]

#Labelling
label_changes = c("Is for the admission of a great many new refugees" = "Is for the admission of a great many new refugees", 
                  "Is for the admission of some new refugees" = "Is for the admission of some new refugees",
                  "Is for the deportation of some refugees" = "Is for the deportation of some refugees",
                  "Is for the deportation of a great many refugees" = "Is for the deportation of a great many refugees",
                  "Is for the development of the EU into a common state" = "Is for the development of the EU into a common state",
                  "Is for stronger cooperation within the EU" = "Is for stronger cooperation within the EU",
                  "Is for weaker cooperation within the EU" = "Is for weaker cooperation within the EU",
                  "Is for Germany's withdrawal from the EU" = "Is for Germany's withdrawal from the EU",
                  "Is for much higher taxes on the rich" = "Is for much higher taxes on the rich",
                  "Is for somewhat higher taxes on the rich" = "Is for somewhat higher taxes on the rich",
                  "Is for somewhat lower taxes on the rich" = "Is for somewhat lower taxes on the rich",
                  "Is for much lower taxes on the rich" = "Is for much lower taxes on the rich",
                  "Is for much more free trade and globalization" = "Is for much more free trade and globalization",
                  "Is for somewhat more free trade and globalization" = "Is for somewhat more free trade and globalization",
                  "Is for somewhat less free trade and globalization" = "Is for somewhat less free trade and globalization",
                  "Is for much less free trade and globalization" = "Is for much less free trade and globalization",
                  "Priority1" = "Fight political corruption",
                  "Priority2" = "Overthrow the political elite",
                  "Priority3" = "Strengthen direct democracy (e.g., through referendums)",
                  "Priority4" = "Defend citizens' interests",
                  "Priority5" = "Lead Germany out of the crisis",
                  "Priority6" = "Improve environmental protection",
                  "Priority7" = "Promote economic growth",
                  "Priority8" = "Strengthen social justice",
                  "Priority9" = "Stop Islamization",
                  "Priority10" = "Fight crime",
                  "Priority11" = "Strengthen civil rights and civil liberties",
                  "Priority12" = "Make globalization fairer",
                  "Priority13" = "Create a social Europe")

brackets <- list(c("Position on \nRefugees", "Is for the admission of a great many new refugees", "Is for the deportation of a great many refugees"),
                 c("Position on \nEuropean Union", "Is for the development of the EU into a common state", "Is for Germany's withdrawal from the EU"),
                 c("Position on \nTaxes", "Is for much higher taxes on the rich", "Is for much lower taxes on the rich"),
                 c("Position on \nGlobalization", "Is for much more free trade and globalization", "Is for much less free trade and globalization"),
                 c("Populist \nPriorities", "Fight political corruption", "Lead Germany out of the crisis"),
                 c("Other \nPriorities", "Improve environmental protection", "Create a social Europe"))

#Produce Figure 1 in the article
p={dwplot(results_main, dot_args = list(size = 3)) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") +
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") +
    ggtitle("") + scale_color_manual(values = c("black")) +
    theme(plot.title = element_text(face="bold"),
          legend.position = "none",
          axis.text=element_text(size=12,colour="black"),axis.title=element_text(size=12))} %>%
  add_brackets(brackets, face = "bold") 

pdf("Graphs/Figure 1.pdf", width = 12, height = 8) # Open a new pdf file
p
dev.off()


########################################################
#FA models for populist valence and populist positions
########################################################

#Create matrix for populist valence
fa_valence_matrix <- conjoint_2017 %>% select_("lfdn", "pop1_volksabstimmungen", "pop2_buerger_vs_politiker", "pop3_einfacher_buerger", "pop4_parteien", "pop5_responsivitaet_bundestag", "pop6_einigkeit_buerger", "pop7_buerger_vs_politiker2", "pop8_kompromiss_verrat")
fa_valence_matrix <-aggregate(fa_valence_matrix, by=list(fa_valence_matrix$lfdn), FUN=mean, na.rm=TRUE)
fa_valence_matrix_reduced <- as.matrix(fa_valence_matrix[, 3:10])

#Run exploratory factor analysis and produce Figure A2.1 in the Online Appendix
pdf("Graphs/Figure A2.1.pdf", width = 8, height = 8) # Open a new pdf file
scree(fa_valence_matrix_reduced)
dev.off()
random.polychor.pa(nrep=10, data.matrix=fa_valence_matrix_reduced, q.eigen=.99)
factanal_populist_valence <- fa(fa_valence_matrix_reduced, nfactors = 1, scores = "regression", cor = "poly")
Table_A1.1_l <- as.matrix(round(factanal_populist_valence$loadings[1:8], digits=3))
Table_A1.1_l <- as.matrix(append(Table_A1.1_l, round(factanal_populist_valence$Vaccounted[1:2], digits=3)))

#Assign factor scores to individuals
scores <- as.data.frame(cbind(fa_valence_matrix$lfdn, factanal_populist_valence$scores))
names(scores)[names(scores)=="V1"] <- "lfdn"
names(scores)[names(scores)=="MR1"] <- "populist_valence"
conjoint_2017 <- merge(conjoint_2017, scores, by="lfdn")

#Create matrix for populist positions
fa_position_matrix <- conjoint_2017 %>% select_("lfdn", "europ_union_mitgliedschaft", "europ_vereinigung", "globalisierung", "fluechtlinge_krieg", "einwanderer", "reiche")
fa_position_matrix <- data.frame(lapply(fa_position_matrix, function(x) as.numeric(x)))
fa_position_matrix <-aggregate(fa_position_matrix, by=list(fa_position_matrix$lfdn), FUN=mean, na.rm=TRUE)
fa_position_matrix_reduced <- as.matrix(fa_position_matrix[, 3:8])

#Run exploratory factor analysis and produce Figure A2.2 in the Online Appendix
scree(fa_position_matrix_reduced)
random.polychor.pa(nrep=10, data.matrix=fa_position_matrix_reduced, q.eigen=.99)
factanal_populist_position <- fa(fa_position_matrix_reduced, nfactors = 1, scores = "regression", cor = "poly")
factanal_populist_position <- fa(fa_position_matrix_reduced[, c(-6)], nfactors = 1, scores = "regression", cor = "poly")
pdf("Graphs/Figure A2.2.pdf", width = 8, height = 8) # Open a new pdf file
scree(fa_position_matrix_reduced[, c(-6)])
dev.off()
random.polychor.pa(nrep=10, data.matrix=fa_position_matrix_reduced[, c(-6)], q.eigen=.99)
Table_A1.1_r <- as.matrix(round(factanal_populist_position$loadings[1:5], digits=3))
Table_A1.1_r <- as.matrix(append(Table_A1.1_r, c("-", "-", "-")))
Table_A1.1_r <- as.matrix(append(Table_A1.1_r, round(factanal_populist_position$Vaccounted[1:2], digits=3)))

#Export Table A1.1 in the Online Appendix
Table_A1.1 <- as.data.frame(cbind(Table_A1.1_l, Table_A1.1_r), row.names = c("Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "SS loadings", "Variance accounted"))
names(Table_A1.1)[names(Table_A1.1) == "V1"] <- "thin_populism"
names(Table_A1.1)[names(Table_A1.1) == "V2"] <- "thick_populism"
print.xtable(xtable(Table_A1.1, digits = (0)), type="html", file="Tables/Table A1.1.html", caption.placement = "top", append = FALSE)

#Assign factor scores to individuals
scores <- as.data.frame(cbind(fa_position_matrix$lfdn, factanal_populist_position$scores))
names(scores)[names(scores)=="V1"] <- "lfdn"
names(scores)[names(scores)=="MR1"] <- "populist_position"
conjoint_2017 <- merge(conjoint_2017, scores, by="lfdn")

#Correlation between factor scores - mentioned in the article
cor(conjoint_2017$populist_position, conjoint_2017$populist_valence)

#Test number of factors if all items are included simultaneously
items <- conjoint_2017 %>% select_("lfdn", "pop1_volksabstimmungen", "pop2_buerger_vs_politiker", "pop3_einfacher_buerger", "pop4_parteien", "pop5_responsivitaet_bundestag", "pop6_einigkeit_buerger", "pop7_buerger_vs_politiker2", "pop8_kompromiss_verrat", "europ_union_mitgliedschaft", "europ_vereinigung", "globalisierung", "fluechtlinge_krieg", "einwanderer", "reiche")
items <- data.frame(lapply(items, function(x) as.numeric(x)))
items <- aggregate(items, by=list(items$lfdn), FUN=mean, na.rm=TRUE)
items_reduced <- as.matrix(items[,3:16])
scree(items_reduced)
factanal_items <- fa(items_reduced, nfactors = 2, scores = "regression", cor = "poly")


#################################
#Run subgroup conjoint analyses
#################################

#Create subgroups
conjoint_2017$populist_cat[conjoint_2017$populist_valence >= 0 & conjoint_2017$populist_position >= 0] <- 4
conjoint_2017$populist_cat[conjoint_2017$populist_valence < 0 & conjoint_2017$populist_position >= 0] <- 3
conjoint_2017$populist_cat[conjoint_2017$populist_valence >= 0 & conjoint_2017$populist_position < 0] <- 2
conjoint_2017$populist_cat[conjoint_2017$populist_valence < 0 & conjoint_2017$populist_position < 0] <- 1
conjoint_2017$populist_cat <- factor(conjoint_2017$populist_cat,
                                     levels = c(1,2,3,4),
                                     labels = c("Non-populists", "Thin populists", "Thick populists", "Thin-thick populists"))

#Conjoint analysis by subgroup
results_subgroups <- cj(praeferenz ~ 
                          A1_refugees + 
                          A2_EU+
                          A3_tax + 
                          A4_trade +
                          B1_corruption + B2_elite + B3_democracy + B4_citizens + B5_crisis + B6_environment + B7_growth + B8_justice + B9_islamization + C1_crime + C2_liberties + C3_globalization + C4_europe, 
                        data = conjoint_2017, id = ~lfdn, weights = ~weight_wave3, estimate = "mm", by = ~populist_cat)

names(results_subgroups)[names(results_subgroups)=="level"]="term"
names(results_subgroups)[names(results_subgroups)=="populist_cat"]="model"
results_subgroups_populist_positions <- results_subgroups %>% filter(term == "Is for the deportation of a great many refugees" | term == "Is for Germany's withdrawal from the EU" | term == "Is for much higher taxes on the rich" | term == "Is for much less free trade and globalization")
results_subgroups_populist_priorities <- results_subgroups %>% filter(term == "Priority1" | term == "Priority2" | term == "Priority3" | term == "Priority4" | term == "Priority5")

#Produce Figure 2.1 in the article
p_subgroups_populist_positions={dwplot(results_subgroups_populist_positions, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.2, 0.85) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22", "grey22", "grey22")) + scale_shape_manual(values = c(0, 20, 19, 15)) +
    theme(plot.title = element_text(face="bold"),
          legend.position = c(0.85, 0.15),
          legend.title = element_blank(),
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure 2.1.pdf", width = 11, height = 5) # Open a new pdf file
p_subgroups_populist_positions
dev.off()

#Produce Figure 2.2 in the article
p_subgroups_populist_priorities={dwplot(results_subgroups_populist_priorities, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.2, 0.85) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22", "grey22", "grey22")) + scale_shape_manual(values = c(0, 20, 19, 15)) +
    theme(plot.title = element_text(face="bold"),
          legend.position = c(0.80, 0.15),
          legend.title = element_blank(),
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure 2.2.pdf", width = 11, height = 5) # Open a new pdf file
p_subgroups_populist_priorities
dev.off()


##########################################
#Run conjoint analyses by vote intention
##########################################

#Create indicator for Die Linke and AfD voters
conjoint_2017$party[conjoint_2017$sonntagsfrage == "Die Linke"] <- 1
conjoint_2017$party[conjoint_2017$sonntagsfrage == "AfD"] <- 2
conjoint_2017$party <- factor(conjoint_2017$party,
                                     levels = c(1,2),
                                     labels = c("Linke", "AfD"))

#Conjoint analysis by vote intention
results_subgroups <- cj(praeferenz ~ 
                          A1_refugees + 
                          A2_EU+
                          A3_tax + 
                          A4_trade +
                          B1_corruption + B2_elite + B3_democracy + B4_citizens + B5_crisis + B6_environment + B7_growth + B8_justice + B9_islamization + C1_crime + C2_liberties + C3_globalization + C4_europe, 
                        data = conjoint_2017, id = ~lfdn, weights = ~weight_wave3, estimate = "mm", by = ~party)

names(results_subgroups)[names(results_subgroups)=="level"]="term"
names(results_subgroups)[names(results_subgroups)=="party"]="model"
results_subgroups_populist_positions <- results_subgroups %>% filter(term == "Is for the deportation of a great many refugees" | term == "Is for Germany's withdrawal from the EU" | term == "Is for much higher taxes on the rich" | term == "Is for much less free trade and globalization")
results_subgroups_populist_priorities <- results_subgroups %>% filter(term == "Priority1" | term == "Priority2" | term == "Priority3" | term == "Priority4" | term == "Priority5")

#Produce Figure A9.1 in the Online Appendix
p_subgroups_populist_positions={dwplot(results_subgroups_populist_positions, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.3, 0.85) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22", "grey22", "grey22")) + scale_shape_manual(values = c(0, 20, 19, 15)) +
    theme(plot.title = element_text(face="bold"),
          legend.position = c(0.9, 0.1),
          legend.title = element_blank(),
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure A9.1.pdf", width = 11, height = 5) # Open a new pdf file
p_subgroups_populist_positions
dev.off()

#Produce Figure A9.2 in the Online Appendix
p_subgroups_populist_priorities={dwplot(results_subgroups_populist_priorities, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.3, 0.85) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22", "grey22", "grey22")) + scale_shape_manual(values = c(0, 20, 19, 15)) +
    theme(plot.title = element_text(face="bold"),
          legend.position = c(0.9, 0.1),
          legend.title = element_blank(),
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure A9.2.pdf", width = 11, height = 5) # Open a new pdf file
p_subgroups_populist_priorities
dev.off()


##################################
#Investigate interaction effects 
##################################

#Create variable for number of thin populist priorities put forward
conjoint_2017$thin_priority1 <- as.numeric(conjoint_2017$B1_corruption) - 1 
conjoint_2017$thin_priority2 <- as.numeric(conjoint_2017$B2_elite) - 1 
conjoint_2017$thin_priority3 <- as.numeric(conjoint_2017$B3_democracy) - 1 
conjoint_2017$thin_priority4 <- as.numeric(conjoint_2017$B4_citizens) - 1 
conjoint_2017$thin_priority5 <- as.numeric(conjoint_2017$B5_crisis) - 1
conjoint_2017$thin_priority_sum <- rowSums(cbind(conjoint_2017$thin_priority1, conjoint_2017$thin_priority2, conjoint_2017$thin_priority3, conjoint_2017$thin_priority4, conjoint_2017$thin_priority5), na.rm = TRUE)

#Conjoint analysis by number of thin populist priorities put forward by candidate
results_interaction <- cj(praeferenz ~ 
                            A1_refugees + 
                            A2_EU+
                            A3_tax + 
                            A4_trade, 
                          data = conjoint_2017, id = ~lfdn, weights = ~weight_wave3, estimate = "mm", by = ~thin_priority_sum)

names(results_interaction)[names(results_interaction)=="level"]="term"
names(results_interaction)[names(results_interaction)=="thin_priority_sum"]="model"
results_interaction_positions <- results_interaction %>% filter(term == "Is for the deportation of a great many refugees" | term == "Is for Germany's withdrawal from the EU" | term == "Is for much higher taxes on the rich" | term == "Is for much less free trade and globalization")

#Produce Figure A12 in the Online Appendix
p_interaction_positions={dwplot(results_interaction_positions, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.3, 0.65) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22", "grey22")) + scale_shape_manual(values = c(1, 2, 0)) +
    theme(plot.title = element_text(face="bold"),
          legend.position = c(0.85, 0.05),
          legend.title = element_blank(),
          legend.direction = "horizontal",
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure A12.pdf", width = 11, height = 5) # Open a new pdf file
p_interaction_positions
dev.off()


###################################
#Check identification assumptions
###################################

#No carryover effects
conjoint_2017$choice_task[conjoint_2017$kandidat == "A"] <- seq(1, 5, by=1)
conjoint_2017$choice_task[conjoint_2017$kandidat == "B"] <- seq(1, 5, by=1)

#Conjoint analysis by choice task (1st to 5th)
results_carryover <- cj(praeferenz ~ 
                          A1_refugees + 
                          A2_EU+
                          A3_tax + 
                          A4_trade +
                          B1_corruption + B2_elite + B3_democracy + B4_citizens + B5_crisis + B6_environment + B7_growth + B8_justice + B9_islamization + C1_crime + C2_liberties + C3_globalization + C4_europe, 
                        data = conjoint_2017, id = ~lfdn, weights = ~weight_wave3, estimate = "mm", by = ~choice_task)

names(results_carryover)[names(results_carryover)=="level"]="term"
names(results_carryover)[names(results_carryover)=="choice_task"]="model"
results_carryover_populist_positions <- results_carryover %>% filter(term == "Is for the deportation of a great many refugees" | term == "Is for Germany's withdrawal from the EU" | term == "Is for much higher taxes on the rich" | term == "Is for much less free trade and globalization")
results_carryover_populist_priorities <- results_carryover %>% filter(term == "Priority1" | term == "Priority2" | term == "Priority3" | term == "Priority4" | term == "Priority5")

#Produce Figure A3.1 in the Online Appendix
p_carryover_populist_positions={dwplot(results_carryover_populist_positions, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.3, 0.70) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22", "grey22", "grey22", "grey22")) + scale_shape_manual(values = c(2, 0, 20, 19, 15)) +
    guides(col = guide_legend(ncol = 3)) + theme(plot.title = element_text(face="bold"),
          legend.position = c(0.85, 0.10),
          legend.title = element_blank(),
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure A3.1.pdf", width = 11, height = 5) # Open a new pdf file
p_carryover_populist_positions
dev.off()

#Produce Figure A3.2 in the Online Appendix
p_carryover_populist_priorities={dwplot(results_carryover_populist_priorities, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.3, 0.70) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22", "grey22", "grey22", "grey22")) + scale_shape_manual(values = c(2, 0, 20, 19, 15)) +
    guides(col = guide_legend(ncol = 3)) + theme(plot.title = element_text(face="bold"),
          legend.position = c(0.85, 0.10),
          legend.title = element_blank(),
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure A3.2.pdf", width = 11, height = 5) # Open a new pdf file
p_carryover_populist_priorities
dev.off()


#No profile-order effects
conjoint_2017$kandidat[conjoint_2017$kandidat == "A"] <- "Candidate A"
conjoint_2017$kandidat[conjoint_2017$kandidat == "B"] <- "Candidate B"

#Conjoint analysis by profile order (candidate on left vs. right side of screen)
results_profile <- cj(praeferenz ~ 
                          A1_refugees + 
                          A2_EU+
                          A3_tax + 
                          A4_trade +
                          B1_corruption + B2_elite + B3_democracy + B4_citizens + B5_crisis + B6_environment + B7_growth + B8_justice + B9_islamization + C1_crime + C2_liberties + C3_globalization + C4_europe, 
                        data = conjoint_2017, id = ~lfdn, weights = ~weight_wave3, estimate = "mm", by = ~kandidat)

names(results_profile)[names(results_profile)=="level"]="term"
names(results_profile)[names(results_profile)=="kandidat"]="model"
results_profile_populist_positions <- results_profile %>% filter(term == "Is for the deportation of a great many refugees" | term == "Is for Germany's withdrawal from the EU" | term == "Is for much higher taxes on the rich" | term == "Is for much less free trade and globalization")
results_profile_populist_priorities <- results_profile %>% filter(term == "Priority1" | term == "Priority2" | term == "Priority3" | term == "Priority4" | term == "Priority5")

#Produce Figure A4.1 in the Online Appendix
p_profile_populist_positions={dwplot(results_profile_populist_positions, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.3, 0.65) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22")) + scale_shape_manual(values = c(3, 4)) +
    theme(plot.title = element_text(face="bold"),
          legend.position = c(0.85, 0.10),
          legend.title = element_blank(),
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure A4.1.pdf", width = 11, height = 5) # Open a new pdf file
p_profile_populist_positions
dev.off()

#Produce Figure A4.2 in the Online Appendix
p_profile_populist_priorities={dwplot(results_profile_populist_priorities, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.3, 0.65) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22")) + scale_shape_manual(values = c(3, 4)) +
    theme(plot.title = element_text(face="bold"),
          legend.position = c(0.85, 0.10),
          legend.title = element_blank(),
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure A4.2.pdf", width = 11, height = 5) # Open a new pdf file
p_profile_populist_priorities
dev.off()


###################################
#Alternative subgroup definition
###################################

#Create alternative subgroups
quantile(conjoint_2017$populist_position, c(0.3333, 0.6667))
quantile(conjoint_2017$populist_valence, c(0.3333, 0.6667))
conjoint_2017$populist_cat_alt[conjoint_2017$populist_valence >= 0.5113382 & conjoint_2017$populist_position >= 0.4674264] <- 4
conjoint_2017$populist_cat_alt[conjoint_2017$populist_valence < -0.4240096 & conjoint_2017$populist_position >= 0.4674264] <- 3
conjoint_2017$populist_cat_alt[conjoint_2017$populist_valence >= 0.5113382 & conjoint_2017$populist_position < -0.4386625] <- 2
conjoint_2017$populist_cat_alt[conjoint_2017$populist_valence < -0.4240096 & conjoint_2017$populist_position < -0.4386625] <- 1
conjoint_2017$populist_cat_alt <- factor(conjoint_2017$populist_cat_alt,
                                     levels = c(1,2,3,4),
                                     labels = c("Non-populists", "Thin populists", "Thick populists", "Thin-thick populists"))

#Conjoint analysis by alternative subgroup
results_subgroups <- cj(praeferenz ~ 
                          A1_refugees + 
                          A2_EU+
                          A3_tax + 
                          A4_trade +
                          B1_corruption + B2_elite + B3_democracy + B4_citizens + B5_crisis + B6_environment + B7_growth + B8_justice + B9_islamization + C1_crime + C2_liberties + C3_globalization + C4_europe, 
                        data = conjoint_2017, id = ~lfdn, weights = ~weight_wave3, estimate = "mm", by = ~populist_cat_alt)

names(results_subgroups)[names(results_subgroups)=="level"]="term"
names(results_subgroups)[names(results_subgroups)=="populist_cat_alt"]="model"
results_subgroups_populist_positions <- results_subgroups %>% filter(term == "Is for the deportation of a great many refugees" | term == "Is for Germany's withdrawal from the EU" | term == "Is for much higher taxes on the rich" | term == "Is for much less free trade and globalization")
results_subgroups_populist_priorities <- results_subgroups %>% filter(term == "Priority1" | term == "Priority2" | term == "Priority3" | term == "Priority4" | term == "Priority5")

#Produce Figure A13.1 in the Online Appendix
p_subgroups_populist_positions={dwplot(results_subgroups_populist_positions, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.2, 0.95) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22", "grey22", "grey22")) + scale_shape_manual(values = c(0, 20, 19, 15)) +
    theme(plot.title = element_text(face="bold"),
          legend.position = c(0.85, 0.15),
          legend.title = element_blank(),
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure A13.1.pdf", width = 11, height = 5) # Open a new pdf file
p_subgroups_populist_positions
dev.off()

#Produce Figure A13.2 in the Online Appendix
p_subgroups_populist_priorities={dwplot(results_subgroups_populist_priorities, dot_args = list(size = 3, aes(colour = model, shape = model))) %>% 
    relabel_predictors(label_changes) + geom_vline(xintercept=0.5, colour = "red") + xlim(0.2, 0.95) + 
    theme_bw() + xlab("Probability that candidate will be chosen") + ylab("") + ggtitle("") +
    scale_color_manual(values = c("grey22", "grey22", "grey22", "grey22")) + scale_shape_manual(values = c(0, 20, 19, 15)) +
    theme(plot.title = element_text(face="bold"),
          legend.position = c(0.80, 0.15),
          legend.title = element_blank(),
          legend.text=element_text(size=12),
          axis.text=element_text(size=14,colour="black"),axis.title=element_text(size=14))}

pdf("Graphs/Figure A13.2.pdf", width = 11, height = 5) # Open a new pdf file
p_subgroups_populist_priorities
dev.off()
